<?php

namespace app\admin\controller;

use gmars\rbac\Rbac;
use think\Cache;
use think\Request;
use think\Session;
use think\Controller;
use think\Db;

class Admin extends Controller
{
    /**
     * 后台主页
     * @return \think\response\View
     */
    public function index()
    {
        $rbacObj = new Rbac();
        // $data = Cache::get('list');
        // if (!$data) {
        //     $data = $this->adminList();
        // }
        // dump($data);

        Session::set('name', input('post.name'));
        $name = Session::get()['name'];

        $id = Db::name('admin')
            ->field('id')
            ->where('name', $name)
            ->find();

        $res = $rbacObj->cachePermission($id['id']);
//        dump($res);

        $request = request();
//        dump($request->post());
        //检测当前 用户 有没有权限 访问者个路由
        $route = $request->routeInfo()['route'];
        $arr = [];
        foreach ($res as $k => $v) {
            array_push($arr, $k);
        }
        if (!in_array($route, $arr)) {
            return $this->error('您木有权限访问此页面');
        }


        $data1 = Db::name('user')->select();
        $count = count($data1);
        $data = Db::name('user')->paginate(2, $count);
// 把分页数据赋值给模板变量list
        $this->assign('da', $data);
        return view('admin/admin');


//        return view('admin/admin', [
//            'data' => $data
//        ]);
    }

    /**
     * 该管理员对应的所有角色
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function roleall($id)
    {
        $list = Db::name('user_role')->alias('ur')
            ->join('role r', 'r.id=ur.role_id')
            ->field(['ur.user_id', 'r.name'])
            ->where('ur.user_id', $id)
            ->select();
        return $list;
    }


    /**
     * 管理员页面
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function administrator()
    {

        //查询所有角色
        $role = Db::name('role')->field(['name', 'id'])->select();
//        dump($role);
        $rows = Db::name('admin')->field(['name', 'id'])->select();


        $this->assign('role', $role);
        $this->assign('rows', $rows);

        return view('admin/administrator');

    }

    /**
     * 添加角色
     * @param $id
     * @param $roles
     * @throws \think\Exception
     */
    public function dorole($id, $roles)
    {
        $rbac = new Rbac();
        $rbac->assignUserRole($id, $roles);

    }


    /**
     * 后台登录
     * @return \think\response\View
     */
    public function adminLogin()
    {
        $token = $this->request->token('__token__', 'sha1');
        Session::set('token', [
            'token' => $token
        ]);

        Cache::set('token', $token, 3600);

//        dump(Cache::get('token'));
//        Session::set('info', [
//            'name' => input("post.name")
//        ]);

//        $name = input("post.name");
//        dump($name);
//        dump($request);

        return view('admin/adminLogin', [
                'token' => $token,]
        );

    }

    /**
     * 验证该账户是否是管理员
     * [checkAdmin description]
     * @return [type] [description]
     */
    public function checkAdmin()
    {
        $admin = Session::get('admin');
        if (empty($admin)) {
            return false;
        }
    }

    /**
     * 用户列表
     * [adminList description]
     * @param  [type] $table [description]
     * @return [type]        [description]
     */
    public function adminList()
    {
        $data = Db::name('user')
            ->field(['mobile', 'email', 'id'])
            // ->cache('list', 3600)
            ->select();
        return $data;
    }

    /**
     * 添加用户
     * @param  [type] $table [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public function doAdd($mobile, $email)
    {
        $data = [
            'mobile' => $mobile,
            'email' => $email,
        ];
        $checkmobile = $this->checkdata('mobile', $data['mobile']);
        $checkemail = $this->checkdata('email', $data['email']);

        if (!$checkmobile) {
            $text = '邮箱或手机重复!';
            $errorInfo = $this->errorInfo($text);
            return $errorInfo;
        }
        if (!$checkemail) {
            $text = '邮箱或手机重复!';
            $errorInfo = $this->errorInfo($text);
            return $errorInfo;
        }

        $rows = Db::name('user')
            ->insert($data);

        if ($rows !== 0) {
            $text = '添加用户成功!';
            $successInfo = $this->successInfo($text);
            return $successInfo;

        } else {
            $text = '添加用户失败!';
            $errorInfo = $this->errorInfo($text);
            return $errorInfo;
        }

    }

    /**
     * 错误信息
     * @return array
     */
    public function errorInfo($text)
    {
        $info = [
            'isError' => 'true',
            'data' => null,
            'error' => [
                'code' => "250",
                'message' => $text
            ]
        ];
        return $info;
    }

    /**
     * 正确信息
     * @return array
     */
    public function successInfo($text)
    {
        $info = [
            'isError' => 'false',
            'data' => '1',
            'error' => [
                'code' => "200",
                'message' => $text
            ]
        ];
        return $info;
    }

    /**
     * 验证mobile email 重复
     * @param $data
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkdata($field, $data)
    {
        $rows = Db::name('user')
            ->where($field, $data)
            ->find();
        if ($rows == null) {
            return true;
        }
    }

    /**
     * 编辑页面
     * @param $id
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit($id)
    {
        $rows = Db::name('user')
            ->where('id', $id)
            ->field(['mobile', 'email'])
            ->find();
        return $rows;
    }


    /**
     * 执行编辑用户
     * [doEdit description]
     * @param  [type] $table [description]
     * @param  [type] $data  [description]
     * @param  [type] $id    [description]
     * @return [type]        [description]
     */
    public function doEdit($mobile, $email, $id)
    {
        $data = [
            'mobile' => $mobile,
            'email' => $email,
        ];
        $rows = Db::name('user')
            ->where('id', $id)
            ->update($data);

        if ($rows !== 0) {
            $text = '编辑用户成功!';
            $successInfo = $this->successInfo($text);
            return $successInfo;

        } else {
            $text = '编辑用户失败!';
            $errorInfo = $this->errorInfo($text);
            return $errorInfo;
        }


    }

    /**
     * 删除用户
     * [doDel description]
     * @param  [type] $table [description]
     * @param  [type] $id    [description]
     * @return [type]        [description]
     */
    public function doDel($id)
    {
        $rows = Db::name('user')
            ->where('id', $id)
            ->delete();

        if ($rows !== 0) {
            $text = '删除用户成功!';
            $successInfo = $this->successInfo($text);
            return $successInfo;

        } else {
            $text = '删除用户失败!';
            $errorInfo = $this->errorInfo($text);
            return $errorInfo;
        }


    }


    /**
     * 分页
     * [page description]
     * @param  [type] $table [description]
     * @return [type]        [description]
     */
    public
    function page($num = 3, $mobile, $email)
    {

        $data = Db::name('user')
            ->field($mobile, $email)
            ->paginate($num);

        if ($data !== 0) {

            $info = [
                'isError' => 'false',
                'data' => '1',
                'error' => 'null'
            ];
            return $info;
        } else {
            $info = [
                'isError' => 'true',
                'data' => null,
                'error' => [
                    'code' => "250",
                    'message' => "分页失败"
                ]

            ];
            return $info;
        }

    }
}